import { _decorator, Component, director } from 'cc';
import { GGStore } from '../../../framework/core/base/GGStore';
import { GAME_INFOS } from '../../../utils/Enums';
import DataMgr from '../../../utils/DataMgr';
const { ccclass } = _decorator;

@ccclass('StaminaManager')
export class StaminaManager extends Component {
    private mainVitalityMax: number = 6;
    private mainVitalityRestoreSecond: number = 120; // 20分钟
    private getVitalityTime: string = "";
    static mainVitalityMax: number = 6;

    start() {
        if (GGStore.get(GAME_INFOS.SAVE_TIME, 100) == 100) {
            DataMgr.currentStamina = this.mainVitalityMax;
            this.getVitalityTime = new Date().toISOString();
            localStorage.setItem("FirstValueGet", "1");
            localStorage.setItem("currentStamina", DataMgr.currentStamina.toString());
            GGStore.set("VitalityTime", Date.now());
        } else {
            DataMgr.currentStamina = GGStore.get(GAME_INFOS.SAVE_TIME);
            this.getVitalityTime = GGStore.get("VitalityTime");
        }
        gg.systemEvent.emit("UpdateMoney");
        director.addPersistRootNode(this.node);
    }

    update(deltaTime: number) {
        if (DataMgr.currentStamina < this.mainVitalityMax) {
            this.restoreVitality();
        }
        else{
            this.getVitalityTime = new Date().toISOString();
        }
    }

    private restoreVitality() {
        const timeSpan = (Date.now() - new Date(this.getVitalityTime).getTime()) / 1000;
        if (timeSpan >= this.mainVitalityRestoreSecond) {
            this.addVitalityByTime(Math.floor(timeSpan / this.mainVitalityRestoreSecond));
            this.getVitalityTime = new Date().toISOString();
            GGStore.set("VitalityTime", this.getVitalityTime);
        } else {
        }
    }

    private addVitalityByTime(number: number) {
        if (DataMgr.currentStamina + number > this.mainVitalityMax) {
            DataMgr.currentStamina = this.mainVitalityMax;
        } else {
            DataMgr.currentStamina += number;
        }
        gg.systemEvent.emit("UpdateMoney");
        GGStore.set(GAME_INFOS.SAVE_TIME, DataMgr.currentStamina);
    }

    

    public subMainVitality() {
        if (DataMgr.currentStamina > 0) {
            DataMgr.currentStamina--;
            localStorage.setItem("currentStamina", DataMgr.currentStamina.toString());
        }
        GGStore.set(GAME_INFOS.SAVE_TIME, DataMgr.currentStamina);
    }

    public static addMainVitality(amount: number) {
        if (DataMgr.currentStamina + amount > this.mainVitalityMax) {
            DataMgr.currentStamina = this.mainVitalityMax;
        } else {
            DataMgr.currentStamina += amount;
        }
        gg.systemEvent.emit("UpdateMoney");
        GGStore.set(GAME_INFOS.SAVE_TIME, DataMgr.currentStamina);
    }
}
